package views.others;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;

import views.slidingMenu.HorzScrollWithActivityMenu;
import views.slidingMenu.R;
import webservice.RESTfulClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;



import database.DatabaseHelpers.VIPmeSQLiteHelper;
import database.Models.Action;
import database.Models.Location;
import database.Models.User;
import database.databaseAccessObjects.DAOAction;
import database.databaseAccessObjects.DAOCheckIn;
import database.databaseAccessObjects.DAOLocation;

public class Refresh extends Activity {
	ProgressDialog progressBar;
	private int progressBarStatus = 0;
	private Handler progressBarHandler = new Handler();
	DAOLocation daolocation;
	DAOCheckIn daocheckin;

	DAOAction daoaction;
	private int fileSize = 0;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		daolocation = new DAOLocation(this);
    	daolocation.open();
    	daocheckin = new DAOCheckIn(this);
    	daocheckin.open();
    	daoaction = new DAOAction(this);
    	daoaction.open();
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
		//setContentView(R.layout.activity_splash_screen);
    	
		progressBar = new ProgressDialog(this);
		progressBar.setCancelable(true);
		progressBar.setMessage("Daten werden aktualisiert");
		progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressBar.setProgress(0);
		progressBar.setMax(100);
		progressBar.show();

		// reset progress bar status
		progressBarStatus = 0;

		// reset filesize
		fileSize = 0;

		new Thread(new Runnable() {
			public void run() {
				while (progressBarStatus < 100) {

					// process some tasks
					//progressBarStatus = refreshActions();
					progressBarStatus = refreshDB();

					// your computer is too fast, sleep 1 second
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					// Update the progress bar
					progressBarHandler.post(new Runnable() {
						public void run() {
							progressBar.setProgress(progressBarStatus);
						}
					});
				}

				// ok, file is downloaded,
				if (progressBarStatus >= 100) {

					// sleep 2 seconds, so that user can see the 100%
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					// close the progress bar dialog
					progressBar.dismiss();
					
	    		   closeScreen();
				}
			}
		}).start();
	
	}

	/**Normalerweise passiert hier mehr
	*alle nur fake
	**/
	public int refreshDB() {

		while (fileSize < 100) {
			 

			

 
			if (fileSize == 0) {
				User user = User.getInstance();
				System.out.println("hhhhhhhhhhhhhhhh"+user.getUserName()+" pw: "+user.getPassword());
				ArrayList<HashMap<String, Object>> mylist = null;
		    	 try {
					mylist = new RESTfulClient().serverGetLocationsAndVisits(user.getUserName(), user.getPassword());
					
		    	 } catch (IOException e) {

					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    	 /**
		    	  * data retrieved from webservice -> clear old data
		    	  */
		    	 VIPmeSQLiteHelper helper = new VIPmeSQLiteHelper(this);
					SQLiteDatabase database = helper.getWritableDatabase();
					helper.clearLocationsAndCheckins(database);
					helper.close();
					
				for (int i = 0; i < mylist.size(); i++) {
					HashMap<String, Object> map = mylist.get(i);
					Location tmploc = daolocation.createLocation((String) map.get("disco"));
				
					JSONArray checkins =  (JSONArray) map.get("gebucht_am");
					JSONArray points =  (JSONArray) map.get("punkte");
					for (int c = 0; c < checkins.length(); c++) {
				
						try {
							if(!checkins.getString(c).isEmpty() && !points.getString(c).isEmpty()){
								System.out.println("---->"+points.getString(c));
							daocheckin.createCheckIn(tmploc.getId(),checkins.getString(c),Integer.parseInt(points.getString(c)));
							
							}
							} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				 fileSize = 50;
				return fileSize;
			} else if (fileSize == 50) {
				
				ArrayList<HashMap<String, Object>> actions = null;
			   	 try {
						actions = new RESTfulClient().serverGetLocationAndActions();
						
			   	 } catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			   	 for (int i = 0; i < actions.size(); i++) {
			   		
					daoaction.createAction((String)actions.get(i).get("name"),(String)actions.get(i).get("text"),Integer.parseInt((String)actions.get(i).get("location")));
			   	 }
			   	 fileSize = 100;
			   return fileSize;
					}
					 
			
			}

				return 100;
			
			
 
		
		
			
			
			
		
		

			//System.out.println(map.get("gebucht_am").getClass()+"->"+ map.get("gebucht_am"));
		
		// create tables and Save the new dummy data to the database
//    	if(daolocation.getAllLocations().size()==0){
//    	String[] diskos = new String[] { "MPark", "P1", "NAGA" };
//	
//		int i = 0;
//		while(i<diskos.length){
//		daolocation.createLocation(diskos[i]);
//		i++;
//		}	
//		List<Location> locations = daolocation.getAllLocations();
//		//add some checkins to each location
//		Location tmploc = locations.get(0);
//		System.out.println(tmploc.getId());
//		
//		daocheckin.createCheckIn(tmploc.getId(), "13.02.2012", 10);
//		daocheckin.createCheckIn(tmploc.getId(), "25.07.2012", 10);
//		daocheckin.createCheckIn(tmploc.getId(), "12.09.2012", 10);
//		daocheckin.createCheckIn(tmploc.getId(), "01.10.2012", 10);
//		tmploc = locations.get(1);
//		daocheckin.createCheckIn(tmploc.getId(), "19.02.2012", 10);
//		daocheckin.createCheckIn(tmploc.getId(), "01.07.2012", 10);
//		tmploc = locations.get(2);
//		daocheckin.createCheckIn(tmploc.getId(), "20.10.2012", 30);
		
    	//}
		
	}
public int refreshActions() {
		
//		User user = User.getInstance();
//		System.out.println("hhhhhhhhhhhhhhhh"+user.getUserName()+" pw: "+user.getPassword());
//		ArrayList<HashMap<String, Object>> mylist = null;
//    	 try {
//			mylist = new RESTfulClient().serverGetLocationsAndVisits(user.getUserName(), user.getPassword());
//			
//    	 } catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//    	 /**
//    	  * data retrieved from webservice -> clear old data
//    	  */
//    	 VIPmeSQLiteHelper helper = new VIPmeSQLiteHelper(this);
//			SQLiteDatabase database = helper.getWritableDatabase();
//			helper.clearLocationsAndCheckins(database);
//			helper.close();
//			
//		for (int i = 0; i < mylist.size(); i++) {
//			HashMap<String, Object> map = mylist.get(i);
//			Location tmploc = daolocation.createLocation((String) map.get("disco"));
//		
//			JSONArray checkins =  (JSONArray) map.get("gebucht_am");
//			JSONArray points =  (JSONArray) map.get("punkte");
//			for (int c = 0; c < checkins.length(); c++) {
//		
//				try {
//					if(!checkins.getString(c).isEmpty() && !points.getString(c).isEmpty()){
//						System.out.println("---->"+points.getString(c));
//					daocheckin.createCheckIn(tmploc.getId(),checkins.getString(c),Integer.parseInt(points.getString(c)));
//				
//					}
//					} catch (JSONException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//			}
	daoaction.createAction("test", "testtext",1);
		return 50;
}
		
	@Override
	protected void onResume() {
		super.onResume();
		daocheckin.open();
		daolocation.open();
		daoaction.open();
	}
	   private void closeScreen() {
		   Intent i = new Intent(Refresh.this, HorzScrollWithActivityMenu.class);
		    
		    startActivity(i);
	        
	        finish();
	    }

	@Override
	protected void onPause() {
		super.onPause();
		daocheckin.close();
		daolocation.close();
		daoaction.close();
		onBackPressed();
	}
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition( R.anim.left, R.anim.right);
		 
		
	}
}
